from flask import current_app
from .models import Category, Tag, Article, Link
from .config import website
from sqlalchemy import desc

# 注册全局函数
def get_config(name):
    return website.get(name) or ''

# 获取分类列表
def get_category():
    try:
        category = Category.query.order_by(Category.sort.asc()).all()
    except Exception as e:
        current_app.logger.error(e)
    return category or []

# 获取标签列表
def get_tags():
    try:
        tag = Tag.query.order_by(Tag.id.asc()).all()
    except Exception as e:
        current_app.logger.error(e)
    return tag or []

# 获取文章列表
def get_articles(**args):
    where = []
    if "is_state" in args:
        # 是否推荐
        where.append(Article.is_state==1)

    order_by = []
    if "sort" in args:
        # 是否拍讯
        order_by.append(desc(args.get('sort')))
    
    limit = 20
    if "limit" in args:
        limit =  args.get("limit")
    try:
        article = Article.query.filter(*where).order_by(*order_by).order_by(Article.id.desc()).limit(limit).all()
    except Exception as e:
        current_app.logger.error(e)

    return article or []

# 获取友情链接
def get_links():
    try:
        link = Link.query.order_by(Link.sort.asc()).all()
    except Exception as e:
        current_app.logger.error(e)
    
    return link or []

''' 初始化 '''
def init_func(app):
    app.add_template_global(get_config, 'get_config')
    app.add_template_global(get_category, 'get_category')
    app.add_template_global(get_tags, 'get_tags')
    app.add_template_global(get_articles, 'get_articles')
    app.add_template_global(get_links, 'get_links')